﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Collections.Generic;

using Microsoft.AspNetCore.Mvc;
using ZhonTai.DynamicApi.Attributes;
using ZhonTai.Industry.Core.Consts;
using ZhonTai.Admin.Services;
using ZhonTai.DynamicApi;
using ZhonTai.Industry.Domain.StationPlc;
using ZhonTai.Admin.Core.Dto;
using ZhonTai.Industry.Services.StationPlc.Dto;
using ZhonTai.Industry.Services.WorkStationPlc;
using ZhonTai.Industry.Services.StationPlc.Dto.Output;
using ZhonTai.Industry.Services.StationPlc.Dto.Input;
using ZhonTai.Industry.Services.WorkStation.Dto.Input;
using ZhonTai.Industry.Services.StationFeature.Dto.Output;
using ZhonTai.Industry.Domain.StationFeature;

namespace ZhonTai.Industry.Services.StationPlc
{
    /// <summary>
    /// PLC设备关联服务
    /// </summary>
    [DynamicApi(Area = IndustryConsts.AreaName)]
    public class StationPlcService : BaseService, IStationPlcService, IDynamicApi
    {
        private IStationPlcRepository _workStationPlcRepository;

        public StationPlcService(IStationPlcRepository stationPlcRepository)
        {
            _workStationPlcRepository = stationPlcRepository;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<StationPlcGetOutput> GetAsync(long id)
        {
            var output = await _workStationPlcRepository.GetAsync<StationPlcGetOutput>(id);
            return output;
        }

        /// <summary>
        /// 查询工站Id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<StationPlcGetOutput> GetStationAsync(long id)
        {
            var output = await _workStationPlcRepository.Select
        .ToOneAsync(a => new StationPlcGetOutput
        {
            WorkStationIds = _workStationPlcRepository.Select.OrderBy(a => a.Id).ToList(b => b.WorkStation.Id)
        });
            return output;
        }

        /// <summary>
        /// 列表查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IEnumerable<StationPlcGetListOutput>> GetListAsync(StationPlcGetListInput input)
        {
            var list = await _workStationPlcRepository.Select
                .OrderByDescending(a => a.Id)
                .ToListAsync<StationPlcGetListOutput>();
            return list;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<StationPlcGetPageOutput>> GetPageAsync(PageInput<StationPlcGetPageInput> input)
        {
            var filter = input.Filter;
            var select = _workStationPlcRepository.Select
                .WhereDynamicFilter(input.DynamicFilter)
                .WhereIf(filter.PlcDeivceId.HasValue && filter.PlcDeivceId > 0, w => w.PLCDeviceId == filter.PlcDeivceId)
                .Count(out var total);
            if (input.SortList != null && input.SortList.Count > 0)
            {
                input.SortList.ForEach(sort =>
                {
                    select = select.OrderByPropertyNameIf(sort.Order.HasValue, sort.PropName, sort.IsAscending.Value);
                });
            }
            else
            {
                select = select.OrderBy(a => a.Sort);
            }
            var list = await select.OrderByDescending(c => c.Id)
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync(t => new StationPlcGetPageOutput() { StationCode = t.WorkStation.StationCode, DeviceName = t.PLCDevice.DeviceName });
            var data = new PageOutput<StationPlcGetPageOutput> { List = list, Total = total };

            return data;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<long> AddAsync(StationPlcAddInput input)
        {
            if (input != null && input.WorkStationIds.Any())
            {
                // 先获取所有已存在的 StationId 和 FeatureId 组合
                var existingStationPlcs = await _workStationPlcRepository.Select
                    .Where(a => input.WorkStationIds.Contains(a.WorkStationId))
                    .ToListAsync();

                // 获取已经存在的 StationId 列表
                var existingStationIds = existingStationPlcs.Select(e => e.WorkStationId).ToHashSet();

                // 过滤掉已经存在的记录，只插入新的记录
                var stationPlcs = input.WorkStationIds
                    .Where(s => !existingStationIds.Contains(s))  // 排除已经存在的 StationId
                    .Select(s => new StationPlcEntity
                    {
                        WorkStationId = s,
                        PLCDeviceId = input.PLCDeviceId,
                        Port = input.Port,
                        RackId = input.RackId,
                        SlotId = input.SlotId,
                        Sort = input.Sort,
                        IpAddress = input.IpAddress,
                        Enabled = true
                    })
                    .ToList();

                // 如果有新数据需要插入
                if (stationPlcs.Any())
                {
                    var result = await _workStationPlcRepository.InsertAsync(stationPlcs);
                    return result.Last().Id;  // 返回最后插入的 ID
                }
            }
            return -1;  // 如果没有新数据需要插入，返回 -1
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task UpdateAsync(StationPlcUpdateInput input)
        {
            var entity = await _workStationPlcRepository.GetAsync(input.Id);
            if (!(entity?.Id > 0))
            {
                throw ResultOutput.Exception("PLC设备关联不存在！");
            }

            Mapper.Map(input, entity);
            await _workStationPlcRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<bool> DeleteAsync(long id)
        {
            return await _workStationPlcRepository.DeleteAsync(id) > 0;
        }

        /// <summary>
        /// 软删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<bool> SoftDeleteAsync(long id)
        {
            return await _workStationPlcRepository.SoftDeleteAsync(id);
        }

        /// <summary>
        /// 批量软删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<bool> BatchSoftDeleteAsync(long[] ids)
        {
            return await _workStationPlcRepository.SoftDeleteAsync(ids);
        }

        /// <summary>
        /// 设置启用
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task SetEnableAsync(StationPlcSetEnableInput input)
        {
            var entity = await _workStationPlcRepository.GetAsync(input.StationPlcId);
            entity.Enabled = input.Enabled;
            await _workStationPlcRepository.UpdateAsync(entity);
        }
    }
}